from crm import models
from django import forms
from django.core.exceptions import ValidationError
import hashlib
from multiselectfield.forms.fields import MultiSelectFormField


class BSModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for filed in self.fields.values():
            if isinstance(filed, (MultiSelectFormField, forms.BooleanField)):
                continue
            filed.widget.attrs['class'] = 'form-control'


class RegForm(forms.ModelForm):
    password = forms.CharField(
        min_length=6,
        widget=forms.PasswordInput(attrs={'placeholder': '密码', 'autocomplete': 'off'})
    )
    re_password = forms.CharField(
        min_length=6,
        widget=forms.PasswordInput(attrs={'placeholder': '确认密码', 'autocomplete': 'off'})
    )

    class Meta:
        model = models.UserProfile
        fields = '__all__'
        widgets = {
            'username': forms.EmailInput(attrs={'placeholder': '您的邮箱', 'autocomplete': 'off'}),
            'mobile': forms.TextInput(attrs={'placeholder': '您的手机号', 'autocomplete': 'off'}),
            'name': forms.TextInput(attrs={'placeholder': '您的姓名', 'autocomplete': 'off'}),
        }

    def clean(self):
        password = self.cleaned_data.get('password')
        re_password = self.cleaned_data.get('re_password')
        username = self.cleaned_data.get('username')
        user_obj = models.UserProfile.objects.filter(username=username)
        if user_obj:
            self.add_error('username', '用户名已存在')
            raise ValidationError('用户名已存在')
        if password == re_password:
            md5 = hashlib.md5()
            if password:
                md5.update(password.encode('utf-8'))
            self.cleaned_data['password'] = md5.hexdigest()
            return self.cleaned_data
        else:
            self.add_error('re_password', '两次密码不一致')
            raise ValidationError('两次密码不一致!!')


class AddClient(BSModelForm):
    class Meta:
        model = models.Customer
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for filed in self.fields.values():
            if isinstance(filed, MultiSelectFormField):
                continue
            filed.widget.attrs['class'] = 'form-control'


class EditFollow(BSModelForm):
    class Meta:
        model = models.ConsultRecord
        fields = '__all__'

    def __init__(self, request, customer_id, *args, **kwargs):
        """

        :param request: request对象
        :param customer_id: 客户的ID
        :param args:
        :param kwargs:
        """
        super().__init__(*args, **kwargs)
        if customer_id and customer_id != 0:
            # 限制客户列表终止还有销售人员的私户
            self.fields['customer'].choices = [(i.pk, str(i)) for i in models.Customer.objects.filter(pk=customer_id)]
        else:
            self.fields['customer'].choices = [('', '---------')] + [(i.pk, str(i)) for i in
                                                                     request.user_obj.customers.all()]
        # 限制销售只有登录的销售
        self.fields['consultant'].choices = [(request.user_obj.pk, request.user_obj)]
